<?php

namespace app\common\library;

use app\admin\model\DiyPushLogModel;
use app\admin\model\WechatConfigModel;
use EasyWeChat\Factory;
use think\Exception;


class Wechat
{

    protected $app;

    public function __construct($cun_id = 1)
    {

        $wechat_config = WechatConfigModel::get(['cun_id' => $cun_id]);
        if (!$wechat_config) {
            throw new Exception("小程序appid和appSecret未配置");
        }
        $appid = $wechat_config['app_id'];
        $secret = $wechat_config['app_secret'];
        $config = [
            'app_id' => $appid,
            'secret' => $secret,

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            /*'log' => [
                'level' => 'debug',
                'file' => RUNTIME_PATH . 'wechat.log',
            ],*/
        ];

        $this->app = Factory::miniProgram($config);
    }

    public function getApp()
    {
        return $this->app;
    }


    //小程序:获取openid&session_key
    public function code($code)
    {
        return $this->app->auth->session($code);
    }

    public function phoneNumber($code)
    {
        return $this->app->getPhoneNumber($code);
    }

    //解密信息
    public function decryptData($session, $iv, $encryptData)
    {
        return $this->app->encryptor->decryptData($session, $iv, $encryptData);
    }

    public function getAccessToken()
    {
        $accessToken = $this->app->access_token;
        $token = $accessToken->getToken(); // token 数组  token['access_token'] 字符串
        //$token = $accessToken->getToken(true); // 强制重新从微信服务器获取 token.
        return $token['access_token'] ?? '';
    }

    public function sendMessage($push_id, $openid, $templateId, $data, $page = '', $state = '')
    {
        $sendData = [
            'template_id' => $templateId, // 所需下发的订阅模板id
            'touser' => $openid,     // 接收者（用户）的 openid
            'page' => $page,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => $data,         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
            'miniprogram_state' => $state ?: 'formal',//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        ];

        $res = $this->app->subscribe_message->send($sendData);

        $errCode = $res['errcode'] ?? '-1';
        DiyPushLogModel::create([
            'push_id' => $push_id,
            'openid' => $openid,
            'template_id' => $templateId,
            'data' => json_encode($data, JSON_UNESCAPED_UNICODE),
            'page_path' => $page,
            'errcode' => $errCode,
            'result' => json_encode($res, JSON_UNESCAPED_UNICODE)
        ]);
        if ($errCode === 0) {
            return true;
        }

        return false;
    }

}
